package com.link.base.base.opty.service;

import com.link.base.base.opty.dao.mybatis.mapper.OptyItemMapper;
import com.link.base.base.opty.dao.mybatis.mapper.OptyMapper;
import com.link.base.base.opty.model.ApiOptyExtModel;
import com.link.base.base.opty.model.Opty;
import com.link.base.base.opty.model.OptyItem;
import com.link.base.base.order.dao.mybatis.mapper.SaleOrderItemMapper;
import com.link.base.base.order.dao.mybatis.mapper.SaleOrderMapper;
import com.link.base.base.order.model.SaleOrder;
import com.link.base.base.order.model.SaleOrderItem;
import com.link.base.base.product.dao.mybatis.mapper.ProductMapper;
import com.link.base.base.product.model.Product;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.snowflake.GenerateCodeSingleton;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.base.core.basic.util.YmlConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author unknown
 * @date unknown
 * @comments 商机服务
 */
@Service
public class OptyServiceImpl extends BasicServiceImpl<Opty> implements OptyService {
    @Resource
    private OptyMapper optyMapper;
    @Resource
    private OptyItemMapper optyItemMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private SaleOrderMapper saleOrderMapper;
    @Resource
    private SaleOrderItemMapper saleOrderItemMapper;
    @Resource
    private KeyGenerateDao keyGenerateDao;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public BasicMapper<Opty> getBasicMapper() {
        return optyMapper;
    }

    /**
     * 商机转订单
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void optyGenerateOrder(Opty o, Long randomId) throws Exception {
//        String orderNo = keyGenerateDao.keyGenerate().toString();
        //使用GenerateCodeSingleton获取订单编号
        GenerateCodeSingleton generateCodeSingleton = GenerateCodeSingleton.getInstance();
        String orderNo = generateCodeSingleton.getOrderCodeStr();
        SaleOrder order = new SaleOrder();
        //行Id
        order.setId(randomId);
        //订单编号
        order.setOrderNo(orderNo);
        //order.setOptyId(o.getOptyDt());
        //order.setOptyName(o.getOptyName());//商机名称
        // 客户Id
        order.setAcctId(o.getAccntId());
        //商机Id
        //order.setOptyId(o.getId());
        order.setOrderType("销售订单");
        order.setOrgId(o.getOrgId());
        order.setPostnId(o.getPostnId());
        order.setStatus("新建");
        //新建订单头
        saleOrderMapper.insert(order);

        if (o.getProdList() != null) {
            for (OptyItem l : o.getProdList()) {
                SaleOrderItem op = new SaleOrderItem();
                Long productRowId = keyGenerateDao.keyGenerate();
                //头id
                op.setHeadId(randomId);
                //行ID
                op.setId(productRowId);
                //产品id
                op.setProdId(l.getProdId());
                //总金额
                op.setBasePrice(Double.valueOf(l.getPrice()));
                //产品个数
                op.setQty(Double.valueOf(l.getQty()));
                //新建订单行
                saleOrderItemMapper.insert(op);
            }
        }
    }

    /**
     * 商机子模块查询信息时，校验是否能够访问该商机
     */
    @Override
    public void checkOptyIsAccess(Long optyId, String security) throws Exception {
        Opty opty = new Opty();
        opty.setId(optyId);
        opty = optyMapper.queryById(opty);
        if (opty == null || "".equals(opty)) {
            throw new ServiceException("OPTY-001");
        }
    }

    @Override
    public void approvalUpdateOptyStatus(Long objectId, String param1, String param2, String param3, String param4,
                                         String param5) throws Exception {
        Opty queryOpty = new Opty();
        queryOpty.setId(objectId);
        Opty opty = queryById(queryOpty);
        if (opty == null) {
            throw new ServiceException("OPTY-002");
        }
        //审批拒绝
        String refused = "Refused";
        if (refused.equals(param1)) {
            Opty record = new Opty();
            record.setId(objectId);
            record.setStatus(param1);
            optyMapper.optyStatusUpdate(record);
        }
        //审批通过
        String approved = "Approved";
        if (approved.equals(param1)) {
            Opty record = new Opty();
            record.setId(objectId);
            record.setStatus(param1);
            optyMapper.optyStatusUpdate(record);
        }
    }

    @Override
    public List<Opty> queryOptyReport(Opty record) throws Exception {
        List<Opty> list;
        list = optyMapper.queryOptyReportPage(record);
        return list;
    }

    @Override
    public String getOptyReportHtml(Opty record) throws Exception {
        StringBuilder html = new StringBuilder("");
        StringBuilder title = new StringBuilder("");
        String[] optyDetail = null;
        StringBuilder detailContent;
        String[] empArray = null;
        StringBuilder emp;

        title.append("<div id=\"showTableDiv\" class=\"showTableDiv\">");
        title.append("<table id=\"OptyReport-table\" style=\"height: 100%;\" keyFilterDiv=\"keyFilter\">");
        title.append("<tr class=\"titleTr\">");
        title.append("<td width='100' class=\"titleTd\">所属组别</td>");
        title.append("<td width='100' class=\"titleTd\">商机阶段</td>");
        title.append("<td width='100' class=\"titleTd\">商机状态</td>");
        title.append("<td width='100' class=\"titleTd\">成交概率</td>");
        title.append("<td width='100' class=\"titleTd\">所属年份</td>");
        title.append("<td width='100' class=\"titleTd\">金额合计(万)</td>");
        title.append("<td id=\"tdDetailTitle\" class=\"titleTd\">商机明细</td>");
        title.append("<td width='100' class=\"titleTd\">业务人员</td>");
        title.append("</tr>");
        List<Opty> list = optyMapper.queryOptyReportPage(record);
        for (int i = 0; i < list.size(); i++) {
            detailContent = new StringBuilder();
            emp = new StringBuilder();
            if ("mysql".equals(YmlConstants.getApplicationDatabase())) {
                if (list.get(i).getOptyDetail() != null && !"".equals(list.get(i).getOptyDetail())) {
                    optyDetail = list.get(i).getOptyDetail().split("(：；,)|(：；)");
                } else {
                    optyDetail = null;
                }
                if (list.get(i).getEmpDetail() != null && !"".equals(list.get(i).getEmpDetail())) {
                    empArray = list.get(i).getEmpDetail().split("(,,)|(,)");
                } else {
                    empArray = null;
                }
            } else {
                if (list.get(i).getOptyDetail() != null && !"".equals(list.get(i).getOptyDetail())) {
                    optyDetail = list.get(i).getOptyDetail().split("：；");
                } else {
                    optyDetail = null;
                }
                if (list.get(i).getEmpDetail() != null && !"".equals(list.get(i).getEmpDetail())) {
                    empArray = list.get(i).getEmpDetail().split(",");
                } else {
                    empArray = null;
                }
            }
//          if(list.get(i).getOptyDetail() != null && !"".equals(list.get(i).getOptyDetail())){
//              optyDetail = list.get(i).getOptyDetail().split("：；");
//          }else{
//              optyDetail = null;
//          }
//          if(list.get(i).getEmpDetail() != null && !"".equals(list.get(i).getEmpDetail())){
//              empArray = list.get(i).getEmpDetail().split(",");
//          }else{
//              empArray = null;
//          }
            html.append("<tr class=\"conTr\">");
            html.append("<td id=\"tdManagerOrgName\" width='100' class=\"conTd\">" + replaceNullstr(list.get(i).getManagerOrgName()) + "</td>");
            html.append("<td id=\"tdStage\" width='100' class=\"conTd\">" + replaceNullstr(list.get(i).getStage()) + "</td>");
            html.append("<td id=\"tdStatus\" width='100' class=\"conTd\">" + replaceNullstr(list.get(i).getStatus()) + "</td>");
            html.append("<td id=\"tdRate\" width='100' class=\"conTd\">" + replaceNullstr(list.get(i).getRate()) + "</td>");
            html.append("<td id=\"tdYear\" width='100' class=\"conTd\">" + replaceNullstr(list.get(i).getOptyYear()) + "</td>");
            html.append("<td id=\"tdTotalAmount\" width='100' class=\"conTd\">" + replaceNullstr(list.get(i).getTotalAmount()) + "</td>");

//          html.append("<td width='100' class=\"conTd\">"+replaceNullstr(list.get(i).getOptyDetail())+"</td>");
            if (optyDetail != null) {
                for (int j = 0; j < optyDetail.length; j++) {
//                  detailContent = detailContent + "<p class=\"detailContent\">"+replaceNullstr(optyDetail[j])+"</p>";
                    detailContent.append(replaceNullstr(optyDetail[j])).append("<br/>");
                }
            }
            html.append("<td id=\"tdDetailContent\" class=\"conTd\">").append(detailContent).append("</td>");

//          html.append("<td id=\"tdEmpDetail\" width='100' class=\"conTd\">"+replaceNullstr(list.get(i).getEmpDetail())+"</td>");
            if (empArray != null) {
                for (int k = 0; k < empArray.length; k++) {
//                  emp = emp + "<p class=\"empDetail\">"+replaceNullstr(empArray[k])+"</p>";
                    emp.append(replaceNullstr(empArray[k])).append("<br/>");
                }
            }
            html.append("<td id=\"tdEmpDetail\" width='100' class=\"conTd\">").append(emp).append("</td>");
            html.append("</tr>");
        }
        html = title.append(html);
        html.append("</table>");
        html.append("</div>");
        String result = "";
        result = html.toString();
        return result;
    }

    @Override
    public List<Opty> queryOptyReportOrg(Opty record) throws Exception {
        List<Opty> list;
        list = optyMapper.queryOptyReportOrg(record);
        return list;
    }

    @Override
    public List<Opty> queryOptyReportOrgIdByName(Opty record) throws Exception {
        List<Opty> list;
        list = optyMapper.queryOptyReportOrgIdByName(record);
        return list;
    }

    public String replaceNullstr(String str) {
        if (str == null) {
            return "";
        } else {
            return str;
        }
    }

    @Override
    public List<Opty> queryCountAndAmountByMonthAndRate(Opty record) throws Exception {

        return optyMapper.queryCountAndAmountByMonthAndRate(record);
    }

    @Override
    public List<Opty> queryOrgAmountByRate(Opty record) throws Exception {

        if (null == record.getOrgId()) {
            record.setOrgId(UserUtil.getUser().getOrgId());
        }
        return optyMapper.queryOrgAmountByRate(record);
    }

    @Override
    public List<Opty> queryOptyTop10(Opty record) throws Exception {

        return optyMapper.queryOptyTop10(record);
    }

    @Override
    public List<Opty> getOptyList(Opty opty) {
        return optyMapper.getOptyList(opty);
    }

    @Override
    public ApiOptyExtModel getApiOpty(Long optyId) throws Exception {
        if (null == optyId) {
            throw new ServiceException("OPTY-003");
        }
        ApiOptyExtModel entity = new ApiOptyExtModel();
        Opty example = new Opty();
        example.setId(optyId);
        Opty opty = optyMapper.queryById(example);
        if (opty == null) {
            throw new ServiceException("OPTY-004",optyId.toString());
        } else {
            BeanUtils.copyProperties(opty, entity);
            OptyItem optyItem = new OptyItem();
            optyItem.setOptyId(optyId);
            optyItem.setPageFlag(false);
            List<OptyItem> list = optyItemMapper.queryByExamplePage(optyItem);
            if (list == null || list.size() == 0) {
                entity.setOptyItemList(new ArrayList<OptyItem>());
            } else {
                //校验产品是否已同步
                for (int i = 0; i < list.size(); i++) {
                    Long prodId = list.get(i).getProdId();
                    Product product = new Product();
                    product.setId(prodId);
                    Product record = productMapper.queryById(product);
                    if (record != null) {
                        String prodIntegrationId = record.getIntegrationId();
                        //未同步产品,从List中删除
                        if (StringUtils.isBlank(prodIntegrationId)) {
                            list.remove(i);
                        } else {
                            //已同步产品,替换【产品ID】替换为【产品集成ID】
                            list.get(i).setProdId(Long.parseLong(prodIntegrationId));
                        }
                    }
                }
                entity.setOptyItemList(list);
            }
        }
        return entity;
    }
}
